package com.jianwei.web.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

import com.jianwei.web.dao.UserDao;
import com.jianwei.web.pojo.Users;
import com.jianwei.web.util.StrutsUtils;

@Component
@Transactional
public class LoginService {
	@Autowired
	private UserDao userDao;
	
	/**
	 * 检测用户是否登录
	 * @return 登录就返回用户信息,未登录就返回error
	 */
	public JSON checkSession(){
		if(StrutsUtils.getSession().getAttribute("user") != null){
			return JSONObject.fromObject((Users)StrutsUtils.getSession().getAttribute("user"));
		}
		return JSONObject.fromObject("{\"error\":\"error\"}");
	}
	
	/**
	 * 根据 传过来的user信息 来判断该用户是否在数据库中拥有
	 * @param user
	 * @return 有就返回用户信息,没有就返回error
	 */
	public JSON loginUser(Users user){
		String hql = "from Users where user_name = ? and user_pwd = ?";
		List<Users> list = userDao.findByParam(hql,user.getUser_name(),user.getUser_pwd());
		if(!list.isEmpty()){
			StrutsUtils.getSession().getServletContext().setAttribute(user.getUser_name(),"1");
			StrutsUtils.getSession().setAttribute("user", JSONObject.fromObject(list.get(0)));			
			return JSONObject.fromObject(user);
		}
		return JSONObject.fromObject("{\"error\":\"error\"}");
	}
}
